package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.ShippingAddress;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.ShipAddressPo;
import com.kws.merchant.mapper.ShippingAddressMapper;
import com.kws.merchant.service.ShippingAddressService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * 收货地址管理(ShippingAddress)表服务实现类
 *
 * @author yxy
 * @since 2024-10-22 11:03:44
 */
@Service("shippingAddressService")
public class ShippingAddressServiceImpl extends ServiceImpl<ShippingAddressMapper, ShippingAddress> implements ShippingAddressService {

    @Resource
    private ShippingAddressMapper shippingAddressMapper;

    @Override
    public Page<ShippingAddress> getShipAddressList(ShipAddressPo shipAddressPo) {
        LambdaQueryWrapper<ShippingAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ShippingAddress::getUserId, SecurityUtils.getUserId());
        wrapper.eq(ShippingAddress::getEnable, 1);
        Page<ShippingAddress> page = new Page<>(shipAddressPo.getPageSize(), shipAddressPo.getTotalPage());
        return this.page(page, wrapper);
    }

    @Override
    public boolean saveOrUpdateShipAddress(ShippingAddress shippingAddress) {
        shippingAddress.setUserId(SecurityUtils.getUserId());
        //设置该地址为默认地址
        if (shippingAddress.getIsDefault().equals(1)) {
            LambdaQueryWrapper<ShippingAddress> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ShippingAddress::getUserId, shippingAddress.getUserId());
            wrapper.eq(ShippingAddress::getIsDefault, 1);
            wrapper.eq(ShippingAddress::getEnable, 1);
            ShippingAddress address = this.getOne(wrapper);
            if (ObjectUtils.isNotNull(address)) {
                if (!address.getId().equals(shippingAddress.getId())) {
                    address.setIsDefault(0);
                    this.saveOrUpdate(address);
                }
            }
        }
        if (shippingAddress.getId() != null){
            shippingAddress.setEnable("1");
        }
        return this.saveOrUpdate(shippingAddress);
    }

    @Override
    public boolean removeShipAddress(List<Long> ids) {
        LambdaQueryWrapper<ShippingAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.in(ShippingAddress::getId, ids);
        List<ShippingAddress> list = this.list(wrapper);
        if (list != null && list.size() > 0) {
            for (ShippingAddress address : list) {
                address.setEnable("0");
            }
            return this.saveOrUpdateBatch(list);
        }
        return false;
    }


}
